package io.renren.common.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Logger;

@Slf4j
public class SocketServerUtil {

    public static final Integer port = 9001;

    public void init () {
        try {
            //创建一个ServerSocket，port是客户端的端口
            ServerSocket serverSocket = new ServerSocket(port);
            while (true){
                //从请求队列中取出链接,如果只接受一次则不用使用while循环
                Socket socket = serverSocket.accept();
                //获取客户端信息
                BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String clientContent = input.readLine();
                //接下来可以对信息进行操作，我这里是直接打印了，你可以读取或者做其他操作
                System.out.println(clientContent);

                //初始化输出流，回复客户端
                PrintStream out = new PrintStream(socket.getOutputStream());
                //获取键盘输出的内容
                String s = new BufferedReader(new InputStreamReader(System.in)).readLine();
                //将信息发送给客户端
                out.println("open");

                //关闭
                out.close();
                input.close();
            }
        } catch (IOException e) {
            log.error("服务器异常:" + e);
        }
    }


}
